import { encrypt, decrypt } from 'crypto-js/aes';
import { parse } from 'crypto-js/enc-utf8';
import pkcs7 from 'crypto-js/pad-pkcs7';
import NoPadding from 'crypto-js/pad-nopadding';
import ECB from 'crypto-js/mode-ecb';
import CFB from 'crypto-js/mode-cfb';
import md5 from 'crypto-js/md5';
import UTF8 from 'crypto-js/enc-utf8';
import Base64 from 'crypto-js/enc-base64';

export interface EncryptionParams {
  key: string;
  iv: string;
  mode?: 'ECB' | 'CFB';
  padding?: 'pkcs7' | 'NoPadding';
}

const cryptoMode = {
  ECB: ECB,
  CFB: CFB,
};
const cryptoPadding = {
  pkcs7: pkcs7,
  NoPadding: NoPadding,
};
export class AesEncryption {
  private key;
  private iv;
  private mode;
  private padding;

  constructor(opt: Partial<EncryptionParams> = {}) {
    const { key, iv, mode = 'ECB', padding = 'pkcs7' } = opt;
    if (key) {
      this.key = parse(key);
    }
    if (iv) {
      this.iv = parse(iv);
    }
    if (mode) {
      this.mode = cryptoMode[mode] || ECB;
    }
    if (padding) {
      this.padding = cryptoPadding[padding] || pkcs7;
    }
  }

  get getOptions() {
    return {
      mode: this.mode,
      padding: this.padding,
      iv: this.iv,
    };
  }

  encryptByAES(cipherText: string) {
    return encrypt(cipherText, this.key, this.getOptions).toString();
  }

  decryptByAES(cipherText: string) {
    return decrypt(cipherText, this.key, this.getOptions).toString(UTF8);
  }
}

export function encryptByBase64(cipherText: string) {
  return UTF8.parse(cipherText).toString(Base64);
}

export function decodeByBase64(cipherText: string) {
  return Base64.parse(cipherText).toString(UTF8);
}

export function encryptByMd5(password: string) {
  return md5(password).toString();
}
